﻿using System;
using System.Collections.Generic;
using Novacode;
using Resources;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using KPIS.GERP.Models.Class;
using KPIS.GERP.Models.ICM;

namespace KPIS.GERP.WEB.GIMS.Controllers
{
    // [AccessDeniedAuthorize]
    public class InstallmentController : Controller
    {
        private string[] _defaultInclude = new[] {"PurchaseOrder", "DurationType"};
        //
        // GET: /Installment/

        public ActionResult Index(int headerPoId)
        {
            // Installment 
            PurchaseOrderInstallment[] lst;
            ViewBag.HeaderPoId = headerPoId;
            try
            {
                PurchaseOrder purchaseOrder;
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    purchaseOrder = service.Select(new PurchaseOrder {PoId = headerPoId}, null).FirstOrDefault();
                    ViewBag.PurchaseOrder = purchaseOrder;
                    lst = service.SelectPoInstallment(new PurchaseOrderInstallment {PoId = headerPoId}, _defaultInclude);

                    string RecordStatus = purchaseOrder.RecordStatus;
                    ViewBag.bEditable = RecordStatus != Models.SYS.RecordStatus.ApprovedStatus;
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ErrorLocalization.ErrorWhileViewingDetailData + ", " + ex.Message;
                GerpLog.Error(errorMessage);
                ModelState.AddModelError(ErrorLocalization.ErrorWhileViewingDetailData, ex.Message);
                return View(new PurchaseOrderInstallment[0]);
            }
            return View(lst);
        }

        public ActionResult Create(int headerPoId)//, int BidderQuoId)
        {
            var servicePO = new PurchaseOrderService.PurchaseOrderServiceClient();
            ViewBag.HeaderPoId = headerPoId;
            var modelPO = servicePO.Select(new PurchaseOrder() { PoId = headerPoId }, null).FirstOrDefault();
            var model = new PurchaseOrderInstallment {PoId = headerPoId};

            var service1 = new BidService.BidServiceClient();
            var bidderQuotations = service1.SelectBidderQuotation(new BidderQuotation() { BidderId = modelPO.BidderId }
                , new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense", "PurchaseRequestItem.PurchaseRequest", "PurchaseRequestItem.MasResourceItem.MasUnit" });

            foreach (var bidderQuotation in bidderQuotations)
            {
                var RemainQty = bidderQuotation.PurchaseRequestItem.PurchaseRequest.PcTypeId == 1 || bidderQuotation.PurchaseRequestItem.Qty > 1 ? service1.SumQuantity(bidderQuotation.BidderQuoId, model.PoInstallId) : 1;
                var RemainAmount = service1.SumAmount(bidderQuotation.BidderQuoId, model.PoInstallId);
                bidderQuotation.RemainQty = RemainQty;
                bidderQuotation.RemainAmount = RemainAmount;
            }

            ViewBag.BidderQuotation = bidderQuotations;

            return View(model);
        }

        [HttpPost]
        public ActionResult Create(int headerPoId, 
            PurchaseOrderInstallment model, 
            int? currentNumber, 
            FormCollection formCollection,
            int? len = null)
        {
            ViewBag.HeaderPoId = headerPoId;
            model.InstallNumber = currentNumber;
            model.PoId = headerPoId;
            model.RequireDuration = model.DurTypeId == 8 ? len : null;
            model.RequireDate = model.DurTypeId != 8 ? model.RequireDate : null;
            var service1 = new BidService.BidServiceClient();
            var service2 = new PurchaseOrderService.PurchaseOrderServiceClient();

            var qtyInputKey = formCollection.AllKeys.Where(o => o.StartsWith("Qty_"));
            var excludeInputKey = formCollection.AllKeys.Where(o => o.StartsWith("ExcludeVatAmount_"));
            var discountInputKey = formCollection.AllKeys.Where(o => o.StartsWith("DiscountPercent_"));
            var extraInputKey = formCollection.AllKeys.Where(o => o.StartsWith("ExtraDiscount_"));
            var vatInputKey = formCollection.AllKeys.Where(o => o.StartsWith("VatAmount_"));
            var netInputKey = formCollection.AllKeys.Where(o => o.StartsWith("NetAmount_"));

            var itemQty = new Dictionary<int, int>();
            var itemExclude = new Dictionary<int, double>();
            var itemDiscount = new Dictionary<int, double>();
            var itemExtra = new Dictionary<int, double>();
            var itemVat = new Dictionary<int, double>();
            var itemNet = new Dictionary<int, double>();
            foreach(var k in qtyInputKey)
            {
                int key = Convert.ToInt32(k.Split('_')[1]);
                int valueQty = Convert.ToInt32(formCollection[k] ?? "1");
                itemQty.Add(key, valueQty);

                double valueExclude = Convert.ToDouble(formCollection["ExcludeVatAmount_" + key] ?? "0");
                itemExclude.Add(key, valueExclude);

                double valueDiscount = Convert.ToDouble(formCollection["DiscountPercent_" + key] ?? "0");
                itemDiscount.Add(key, valueDiscount);

                double valueExtra = Convert.ToDouble(formCollection["ExtraDiscount_" + key] ?? "0");
                itemExtra.Add(key, valueExtra);

                double valueVat = Convert.ToDouble(formCollection["VatAmount_" + key] ?? "0");
                itemVat.Add(key, valueVat);

                double valueNet = Convert.ToDouble(formCollection["NetAmount_" + key] ?? "0");
                itemNet.Add(key, valueNet);

                var RemainQty = service1.SumQuantity(key, null);
                var RemainAmount = service1.SumAmount(key, null);
                //if (valueQty > RemainQty)
                //{
                //    var modelPO = service2.Select(new PurchaseOrder() { PoId = headerPoId }, null).FirstOrDefault();
                //    var bidderQuotations = service1.SelectBidderQuotation(new BidderQuotation() { BidderId = modelPO.BidderId }
                //        , new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense" });

                //    foreach (var bidderQuotation2 in bidderQuotations)
                //    {
                //        var RemainQty1 = service1.SumQuantity(bidderQuotation2.BidderQuoId, null);
                //        bidderQuotation2.RemainQty = RemainQty1;
                //    }

                //    ViewBag.BidderQuotation = bidderQuotations;
                //    ModelState.AddModelError("", "!จำนวนที่รับในงวดมากกว่าจำนวนที่สั่ง");
                //    return View(model);
                //}

                if (Convert.ToDecimal(valueNet) > RemainAmount)
                {
                    var modelPO = service2.Select(new PurchaseOrder() { PoId = headerPoId }, null).FirstOrDefault();
                    var bidderQuotations = service1.SelectBidderQuotation(new BidderQuotation() { BidderId = modelPO.BidderId }
                        , new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense" });

                    foreach (var bidderQuotation2 in bidderQuotations)
                    {
                        var RemainAmount1 = service1.SumAmount(bidderQuotation2.BidderQuoId, null);
                        bidderQuotation2.RemainAmount = RemainAmount1;
                    }

                    ViewBag.BidderQuotation = bidderQuotations;
                    ModelState.AddModelError("", 
                        string.Format("!จำนวนเงินในงวด {0} บาท มากกว่าจำนวนเงินในใบสั่ง/สัญญา คงเหลือ {1} บาท", 
                        valueNet.ToString(    "#,##0.00#####################################"),
                        RemainAmount.ToString("#,##0.00#####################################")));
                    return View(model);
                }
            }

            var purchaseOrderOfId = service2.Select(new PurchaseOrder {PoId = headerPoId}, null).FirstOrDefault();
            var bidderQuotation = service1.SelectBidderQuotation(new BidderQuotation {BidderId = purchaseOrderOfId.BidderId, Selected = "1"},
                new[] {"PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense"});

            using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
            { 
                var poInstallId = service.InsertPoInstallment(model, Class.GimsMembership.CurrentEmpId);
                foreach (var quotation in bidderQuotation)
                {
                    var itemInQuotation = quotation.PurchaseRequestItem.MasResourceItem;
                    var poinstallmentItem = new PurchaseOrderInstallmentItem();
                    poinstallmentItem.PoInstallId = poInstallId;
                    poinstallmentItem.BidderQuoId = quotation.BidderQuoId;
                    poinstallmentItem.Descr = quotation.Descr;
                    //poinstallmentItem.res = itemInQuotation.ResItemId;
                    var qty = itemQty.FirstOrDefault(o => o.Key == quotation.BidderQuoId).Value;
                    var exclude = itemExclude.FirstOrDefault(o => o.Key == quotation.BidderQuoId).Value;
                    var discount = itemDiscount.FirstOrDefault(o => o.Key == quotation.BidderQuoId).Value;
                    var extra = itemExtra.FirstOrDefault(o => o.Key == quotation.BidderQuoId).Value;
                    var vat = itemVat.FirstOrDefault(o => o.Key == quotation.BidderQuoId).Value;
                    var net = itemNet.FirstOrDefault(o => o.Key == quotation.BidderQuoId).Value;

                    poinstallmentItem.Qty = qty;
                    poinstallmentItem.ExcludeVatAmount = exclude;
                    poinstallmentItem.ItemPriceIncludeVat = (exclude + vat) / (qty <= 0 ? 1 : qty);
                    poinstallmentItem.ItemPriceExcludeVat = exclude / (qty <= 0 ? 1 : qty);
                    poinstallmentItem.NetAmount = net; //(quotation.Price != null ? (double)quotation.Price.Value : 0) * (poinstallmentItem.Qty ?? 0);
                    poinstallmentItem.VatAmount = vat;
                    
                    service.InsertPoInstallmentItem(poinstallmentItem, Class.GimsMembership.CurrentEmpId);
                        
                }
            }
            return RedirectToAction("Index", new { headerPoId = ViewBag.HeaderPoId });
        }

        public ActionResult Edit(int headerPoId, int id)
        {
            ViewBag.HeaderPoId = headerPoId;

            try
            {
                #region old
                //using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                //{
                //    var service1 = new BidService.BidServiceClient();
                //    var model = service.SelectPoInstallment(new PurchaseOrderInstallment {PoInstallId = id}, new[] { "PurchaseOrder" }).FirstOrDefault();
                //    var ItemModels = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem { PoInstallId = id }
                //        , new[] { "BidderQuotation.PurchaseRequestItem.MasResourceItem", "BidderQuotation.PurchaseRequestItem.MasBudgetExpense" });

                //    ViewBag.PurchaseOrderInstallmentItem = ItemModels;
                //    //if (ItemModels != null && ItemModels.Length > 0)
                //    //{
                //    //    ViewBag.ItemQty = service1.SelectBidderQuotation(new BidderQuotation { BidderId = model.PurchaseOrder.BidderId, PrItemId = ItemModels[0].BidderQuotation.PrItemId }, null).Sum(m => m.Qty);
                //    //}
                //    //else
                //    //{
                //    //    ViewBag.ItemQty = "0";
                //    //}
                //    var service2 = new PurchaseOrderService.PurchaseOrderServiceClient();
                //    var purchaseOrderOfId = service2.Select(new PurchaseOrder {PoId = headerPoId}, null).FirstOrDefault(); 
                //    var allBidder = service1.SelectBidder(null, new string[]
                //    {
                //        "PurchaseRequest",
                //        "PurchaseRequest.MasPurchaseMethod",

                //    });

                //    bool isPrIsBid = false;
                //    foreach(var bdr in allBidder)
                //    {
                //        if(bdr.PurchaseRequest != null &&
                //            bdr.PurchaseRequest.MasPurchaseMethod != null &&
                //            bdr.PurchaseRequest.MasPurchaseMethod.IsBid == true &&
                //            bdr.BidderId == purchaseOrderOfId.BidderId)
                //        {
                //            isPrIsBid = true;
                //            break;
                //        }
                //    }

                //    var filterModel = new BidderQuotation
                //        {
                //            BidderId = purchaseOrderOfId.BidderId
                //        };

                //    if(isPrIsBid)
                //    {
                //        filterModel.Selected = "1";
                //    }

                //    var bidderQuotations = service1.SelectBidderQuotation(filterModel,
                //                                                         new[] {"PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense"});

                //    foreach (var bidderQuotation in bidderQuotations)
                //    {
                //        var RemainQty = service1.SumQuantity(bidderQuotation.BidderQuoId, model.PoInstallId);
                //        var RemainAmount = service1.SumAmount(bidderQuotation.BidderQuoId, model.PoInstallId);
                //        bidderQuotation.RemainQty = RemainQty;
                //        bidderQuotation.RemainAmount = RemainAmount;
                //        //var RemainQty = service1.SumQuantity(bidderQuotation.BidderQuoId, model.PoInstallId);
                //        //bidderQuotation.RemainQty = RemainQty;
                //    }
#endregion
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    var service1 = new BidService.BidServiceClient();
                    var modelInstall = service.SelectPoInstallment(new PurchaseOrderInstallment() { PoInstallId = id }, null).FirstOrDefault();
                    var modelItems = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem() { PoInstallId = id }
                        , new[] { "BidderQuotation.PurchaseRequestItem.MasResourceItem", "BidderQuotation.PurchaseRequestItem.MasBudgetExpense", "BidderQuotation.PurchaseRequestItem.PurchaseRequest" });

                    foreach (var modelItem in modelItems)
                    {
                        var RemainQty = modelItem.BidderQuotation.PurchaseRequestItem.PurchaseRequest.PcTypeId == 1 || modelItem.BidderQuotation.PurchaseRequestItem.Qty > 1 ? service1.SumQuantity(modelItem.BidderQuotation.BidderQuoId, modelItem.PoInstallId) : 1;
                        var RemainAmount = service1.SumAmount(modelItem.BidderQuotation.BidderQuoId, modelItem.PoInstallId);
                        modelItem.BidderQuotation.RemainQty = RemainQty;
                        modelItem.BidderQuotation.RemainAmount = RemainAmount;
                    }

                    ViewBag.PurchaseOrderInstallmentItem = modelItems;

                    return View(modelInstall);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ErrorLocalization.ErrorWhileRetreivingDataViaWcf + ", " + ex.Message;
                GerpLog.Error(errorMessage);
                return Content(errorMessage);
            }
        }

        [HttpPost]
        public ActionResult Edit(int headerPoId, PurchaseOrderInstallment model, int? currentNumber, FormCollection formCollection)
        {
            ViewBag.HeaderPoId = headerPoId;
            model.InstallNumber = currentNumber;

            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    var service1 = new BidService.BidServiceClient();
                    var service2 = new PurchaseOrderService.PurchaseOrderServiceClient();

                    var qtyInputKey = formCollection.AllKeys.Where(o => o.StartsWith("Qty_"));
                    var excludeInputKey = formCollection.AllKeys.Where(o => o.StartsWith("ExcludeVatAmount_"));
                    var discountInputKey = formCollection.AllKeys.Where(o => o.StartsWith("DiscountPercent_"));
                    var extraInputKey = formCollection.AllKeys.Where(o => o.StartsWith("ExtraDiscount_"));
                    var vatInputKey = formCollection.AllKeys.Where(o => o.StartsWith("VatAmount_"));
                    var netInputKey = formCollection.AllKeys.Where(o => o.StartsWith("NetAmount_"));

                    var itemPoInstallItemId = new List<int>();
                    var itemQty = new Dictionary<int, int>();
                    var itemExclude = new Dictionary<int, double>();
                    var itemDiscount = new Dictionary<int, double>();
                    var itemExtra = new Dictionary<int, double>();
                    var itemVat = new Dictionary<int, double>();
                    var itemNet = new Dictionary<int, double>();
                    foreach (var k in qtyInputKey)
                    {
                        int valuePoInstallItemId = Convert.ToInt32(k.Split('_')[1]);
                        var key = valuePoInstallItemId;

                        int valueQty = Convert.ToInt32(formCollection[k] ?? "1");
                        itemQty.Add(key, valueQty);
                        itemPoInstallItemId.Add(valuePoInstallItemId);

                        double valueExclude = Convert.ToDouble(formCollection["ExcludeVatAmount_" + key].Length > 0 ? formCollection["ExcludeVatAmount_" + key] : "0");
                        itemExclude.Add(key, valueExclude);

                        double valueDiscount = Convert.ToDouble(formCollection["DiscountPercent_" + key].Length > 0 ? formCollection["DiscountPercent_" + key] : "0");
                        itemDiscount.Add(key, valueDiscount);

                        double valueExtra = Convert.ToDouble(formCollection["ExtraDiscount_" + key].Length > 0 ? formCollection["ExtraDiscount_" + key] : "0");
                        itemExtra.Add(key, valueExtra);

                        double valueVat = Convert.ToDouble(formCollection["VatAmount_" + key].Length > 0 ? formCollection["VatAmount_" + key] : "0");
                        itemVat.Add(key, valueVat);

                        double valueNet = Convert.ToDouble(formCollection["NetAmount_" + key].Length > 0 ? formCollection["NetAmount_" + key] : "0");
                        itemNet.Add(key, valueNet);

                        var poInstallmentItem = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem() { PoInstallItemId = valuePoInstallItemId }, null)
                            .FirstOrDefault();
                        var modelPO = service2.Select(new PurchaseOrder() { PoId = headerPoId }, null).FirstOrDefault();
                        var bidderQuotations = service1.SelectBidderQuotation(new BidderQuotation() { BidderId = modelPO.BidderId }
                            , new[] { "PurchaseRequestItem.MasResourceItem", "PurchaseRequestItem.MasBudgetExpense", "PurchaseRequestItem.PurchaseRequest" }).ToList();
                        var RemainQty = service1.SumQuantity(poInstallmentItem.BidderQuoId, poInstallmentItem.PoInstallId);
                        var RemainAmount = service1.SumAmount(poInstallmentItem.BidderQuoId, poInstallmentItem.PoInstallId);

                        if (bidderQuotations.Count > 0 && bidderQuotations.FirstOrDefault().PurchaseRequestItem.PurchaseRequest.PcTypeId == 1)
                        {
                           
                            //if (valueQty > RemainQty)
                            //{
                            //    var modelItems = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem() { PoInstallId = model.PoInstallId }
                            //        , new[] { "BidderQuotation.PurchaseRequestItem.MasResourceItem", "BidderQuotation.PurchaseRequestItem.MasBudgetExpense" });

                            //    foreach (var modelItem in modelItems)
                            //    {
                            //        var RemainQty1 = service1.SumQuantity(modelItem.BidderQuotation.BidderQuoId, modelItem.PoInstallId);
                            //        var RemainAmount1 = service1.SumAmount(modelItem.BidderQuotation.BidderQuoId, modelItem.PoInstallId);
                            //        modelItem.BidderQuotation.RemainQty = RemainQty;
                            //        modelItem.BidderQuotation.RemainAmount = RemainAmount;
                            //    }

                            //    ViewBag.PurchaseOrderInstallmentItem = modelItems;
                            //    ModelState.AddModelError("", "!จำนวนที่รับในงวดมากกว่าจำนวนที่สั่ง");
                            //    return View(model);
                            //}
                        }
                        if (Convert.ToDecimal(valueNet) > RemainAmount)
                        {
                            var modelItems = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem() { PoInstallId = model.PoInstallId }
                                   , new[] { "BidderQuotation.PurchaseRequestItem.MasResourceItem", "BidderQuotation.PurchaseRequestItem.MasBudgetExpense" });

                            foreach (var modelItem in modelItems)
                            {
                                var RemainQty1 = service1.SumQuantity(modelItem.BidderQuotation.BidderQuoId, modelItem.PoInstallId);
                                var RemainAmount1 = service1.SumAmount(modelItem.BidderQuotation.BidderQuoId, modelItem.PoInstallId);
                                modelItem.BidderQuotation.RemainQty = RemainQty;
                                modelItem.BidderQuotation.RemainAmount = RemainAmount;
                            }

                            ViewBag.PurchaseOrderInstallmentItem = modelItems;
                            ModelState.AddModelError("",
                                string.Format("!จำนวนเงินในงวด {0} บาท มากกว่าจำนวนเงินในใบสั่ง/สัญญา คงเหลือ {1} บาท",
                                valueNet.ToString("#,##0.00#####################################"),
                                RemainAmount.ToString("#,##0.00#####################################")));
                            return View(model);
                        }
                    }

                    foreach (var PoInstallItemId in itemPoInstallItemId)
                    {
                        int nPoInstallItemId = PoInstallItemId;
                        var poInstallmentItem = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem() { PoInstallItemId = nPoInstallItemId }, null).FirstOrDefault();
                        var qty = itemQty.FirstOrDefault(o => o.Key == nPoInstallItemId).Value;
                        var exclude = itemExclude.FirstOrDefault(o => o.Key == nPoInstallItemId).Value;
                        var discount = itemDiscount.FirstOrDefault(o => o.Key == nPoInstallItemId).Value;
                        var extra = itemExtra.FirstOrDefault(o => o.Key == nPoInstallItemId).Value;
                        var vat = itemVat.FirstOrDefault(o => o.Key == nPoInstallItemId).Value;
                        var net = itemNet.FirstOrDefault(o => o.Key == nPoInstallItemId).Value;

                        poInstallmentItem.Qty = qty;
                        poInstallmentItem.ExcludeVatAmount = exclude;
                        poInstallmentItem.ItemPriceIncludeVat = (exclude + vat) / (qty <= 0 ? 1 : qty);
                        poInstallmentItem.ItemPriceExcludeVat = exclude / (qty <= 0 ? 1 : qty);
                        poInstallmentItem.DiscountPercent = discount;
                        poInstallmentItem.ExtraDiscount = extra;
                        poInstallmentItem.VatAmount = vat;
                        poInstallmentItem.NetAmount = net;

                        service.UpdatePoInstallmentItem(poInstallmentItem, Class.GimsMembership.CurrentEmpId);
                    }

                    service.UpdatePoInstallment(model, Class.GimsMembership.CurrentEmpId);
                    return RedirectToAction("Index", new { headerPoId = ViewBag.HeaderPoId });
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ErrorLocalization.ErrorWhileUpdateData + ", " + ex.Message;
                GerpLog.Error(errorMessage);
                return Content(errorMessage);
            }
        }

        public ActionResult Details(int headerPoId, int id)
        {
            ViewBag.HeaderPoId = headerPoId;

            var service3 = new PurchaseOrderService.PurchaseOrderServiceClient();
            var purchaseOrder = service3.Select(new PurchaseOrder { PoId = headerPoId }, null).FirstOrDefault();
            string RecordStatus = purchaseOrder.RecordStatus;
            ViewBag.bEditable = RecordStatus != Models.SYS.RecordStatus.ApprovedStatus;

            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    var service1 = new BidService.BidServiceClient();
                    var model = service.SelectPoInstallment(new PurchaseOrderInstallment { PoInstallId = id }, new[] { "PurchaseOrder" }).FirstOrDefault();
                    var ItemModels = service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem { PoInstallId = id }
                        , new[] { "BidderQuotation.PurchaseRequestItem.MasResourceItem", "BidderQuotation.PurchaseRequestItem.MasBudgetExpense" });

                    ViewBag.PurchaseOrderInstallmentItem = ItemModels;
                    if (ItemModels != null && ItemModels.Length > 0)
                    {
                        ViewBag.ItemQty = service1.SelectBidderQuotation(new BidderQuotation { BidderId = model.PurchaseOrder.BidderId, PrItemId = ItemModels[0].BidderQuotation.PrItemId }, null).Sum(m => m.Qty);
                    }
                    else
                    {
                        ViewBag.ItemQty = "0";
                    }
                    //var model = service.SelectPoInstallment(new PurchaseOrderInstallment { PoInstallId = id }, null).FirstOrDefault();
                    return View(model);
                }
            }
            catch (Exception ex)
            {
                var errorMessage = ErrorLocalization.ErrorWhileUpdateData + ", " + ex.Message;
                GerpLog.Error(errorMessage);
                return Content(errorMessage);
            }
        }

        public ActionResult Delete(int headerPoId, int id)
        {
            ViewBag.HeaderPoId = headerPoId;

            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    foreach (var poInstallItem in service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem { PoInstallId = id }, null))
                    {
                        service.DeletePoInstallmentItem(poInstallItem.PoInstallItemId, Class.GimsMembership.CurrentEmpId);
                    }
                    service.DeletePoInstallment(id, Class.GimsMembership.CurrentEmpId);
                }
                return Redirect("~/Installment/Index?headerPoId=" + headerPoId);
            }
            catch (Exception ex)
            {
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                ModelState.AddModelError("พบข้อผิดพลาด!", "ไม่สามารถลบข้อมูลได้");
                return View("Index");
            }
        }

        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult DeleteAll(int headerPoId, int[] deleteIds)
        {
            ViewBag.HeaderPoId = headerPoId;

            StringBuilder message_error = new StringBuilder();
            message_error.Append("<div class='alert alert-error'>");
            message_error.Append("<button type='button' class='close' data-dismiss='alert'>");
            message_error.Append("<i class='icon-remove'></i>");
            message_error.Append("</button>");
            message_error.Append("<strong>");
            message_error.Append("<i class='icon-remove'></i>");
            message_error.Append(" พบข้อผิดพลาด: ");
            message_error.Append("</strong>");


            if (deleteIds == null)
            {
                message_error.Append("กรุณาเลือกข้อมูลที่ต้องการลบ!");
                message_error.Append("</div>");
                return Json(new {deleteIds = deleteIds, success = false, message = message_error.ToString()});
            }

            try
            {
                using (var service = new PurchaseOrderService.PurchaseOrderServiceClient())
                {
                    foreach (int delete in deleteIds)
                    {
                        foreach (var poInstallItem in service.SelectPoInstallmentItem(new PurchaseOrderInstallmentItem { PoInstallId = delete }, null))
                        {
                            service.DeletePoInstallmentItem(poInstallItem.PoInstallItemId, Class.GimsMembership.CurrentEmpId);
                        }
                        service.DeletePoInstallment(delete, Class.GimsMembership.CurrentEmpId);
                    }

                }

                message_error = new StringBuilder();
                message_error.Append("<div class='alert alert-block alert-success'>");
                message_error.Append("<button type='button' class='close' data-dismiss='alert'>");
                message_error.Append("<i class='icon-remove'></i>");
                message_error.Append("</button>");
                message_error.Append("<strong>");
                message_error.Append("<i class='icon-ok'></i>");
                message_error.Append(" ลบข้อมูล: ");
                message_error.Append("</strong>");
                message_error.Append("ลบข้อมูลเรียบร้อยแล้ว!");
                message_error.Append("</div>");
                ModelState.AddModelError(ErrorLocalization.Error, string.Format("ลบข้อมูลไปทั้งหมด {0} รายการ", deleteIds.Length.ToString("#,##0")));
                return Json(new {success = true, message = message_error.ToString()});
                //return Json(new { success = true });
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(ErrorLocalization.Error, ErrorLocalization.ErrorWhileDeleteData);
                GerpLog.Error(ErrorLocalization.ErrorWhileDeleteData + ", " + ex.Message);
                return Json(new {success = false});
            }
        }
    }
}